<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <el-icon class="logo-icon"><FolderOpened /></el-icon>
        <h2>军神网盘 网盘系统</h2>
        <p>在线文件管理平台</p>
      </div>
      
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        class="login-form"
        @submit.prevent="handleLogin"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="用户名"
            size="large"
            :prefix-icon="User"
            clearable
          />
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="密码"
            size="large"
            :prefix-icon="Lock"
            show-password
            @keyup.enter="handleLogin"
          />
        </el-form-item>
        
        <el-form-item v-if="needCaptcha" prop="verifyCode">
          <div class="captcha-row">
            <el-input
              v-model="loginForm.verifyCode"
              placeholder="验证码"
              size="large"
              :prefix-icon="Key"
              @keyup.enter="handleLogin"
            />
            <div class="captcha-img" @click="refreshCaptcha">
              <img v-if="captchaImg" :src="captchaImg" alt="验证码" />
              <span v-else>点击获取</span>
            </div>
          </div>
        </el-form-item>
        
        <el-form-item>
          <el-button
            type="primary"
            size="large"
            class="login-button"
            :loading="loading"
            @click="handleLogin"
          >
            {{ loading ? '登录中...' : '登录' }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock, Key } from '@element-plus/icons-vue'
import { userApi } from '@/api'

const router = useRouter()
const route = useRoute()

const loginFormRef = ref(null)
const loading = ref(false)
const needCaptcha = ref(false)
const captchaImg = ref('')
const captchaKey = ref('')

const loginForm = reactive({
  username: '',
  password: '',
  verifyCode: ''
})

const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ],
  verifyCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ]
}

onMounted(async () => {
  // 检查是否已登录
  try {
    const res = await userApi.checkLogin()
    if (res.data?.isLogin) {
      router.push('/home')
    }
  } catch (error) {
    // 未登录，继续显示登录页
  }
})

const getLoginVerifyMode = async (username) => {
  if (!username) return
  
  try {
    const res = await userApi.getLoginVerifyMode(username)
    const mode = res.data
    if (mode === 'IMG_VERIFY_MODE' || mode === 'TWO_FACTOR_AUTHENTICATION_MODE') {
      needCaptcha.value = true
      await refreshCaptcha()
    } else {
      needCaptcha.value = false
    }
  } catch (error) {
    // 忽略错误
  }
}

const refreshCaptcha = async () => {
  try {
    const res = await userApi.getCaptcha()
    if (res.data) {
      captchaImg.value = res.data.img
      captchaKey.value = res.data.key
    }
  } catch (error) {
    ElMessage.error('获取验证码失败')
  }
}

const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  await loginFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    loading.value = true
    try {
      const loginData = {
        username: loginForm.username,
        password: loginForm.password
      }
      
      if (needCaptcha.value) {
        loginData.verifyCode = loginForm.verifyCode
        loginData.captchaKey = captchaKey.value
      }
      
      const res = await userApi.login(loginData)
      
      if (res.data?.token) {
        localStorage.setItem('军神网盘-token', res.data.token)
        ElMessage.success('登录成功')
        
        // 跳转到之前访问的页面或首页
        const redirect = route.query.redirect || '/home'
        router.push(redirect)
      }
    } catch (error) {
      // 登录失败，刷新验证码
      if (needCaptcha.value) {
        await refreshCaptcha()
        loginForm.verifyCode = ''
      }
    } finally {
      loading.value = false
    }
  })
}

// 监听用户名变化，检查是否需要验证码
watch(() => loginForm.username, (newVal) => {
  if (newVal) {
    getLoginVerifyMode(newVal)
  }
})
</script>

<style lang="scss" scoped>
.login-container {
  width: 100%;
  height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
}

.login-box {
  width: 400px;
  padding: 40px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
}

.login-header {
  text-align: center;
  margin-bottom: 40px;
  
  .logo-icon {
    font-size: 48px;
    color: #409eff;
    margin-bottom: 16px;
  }
  
  h2 {
    font-size: 24px;
    color: #303133;
    margin-bottom: 8px;
  }
  
  p {
    font-size: 14px;
    color: #909399;
  }
}

.login-form {
  .captcha-row {
    display: flex;
    gap: 12px;
    
    .el-input {
      flex: 1;
    }
    
    .captcha-img {
      width: 120px;
      height: 40px;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
      overflow: hidden;
      
      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
      
      span {
        font-size: 12px;
        color: #909399;
      }
      
      &:hover {
        border-color: #409eff;
      }
    }
  }
  
  .login-button {
    width: 100%;
    margin-top: 10px;
  }
}
</style>

